package com.alt.adapter;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.alt.R;
import com.alt.connector.RestClient;
import com.alt.handler.CMCmdHandler;
import com.alt.manager.ALTAppMgr;
import com.alt.models.AdsModel;
import com.alt.utils.ALTSysUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ListAdAdapter extends ArrayAdapter<AdsModel> {

	public ArrayList<AdsModel> mApps;
	private Activity context;
	private Map<String, byte[]> mIcons;
	private Drawable mStdImg;
	private NumberFormat formatter = new DecimalFormat("#,###,###");
	private String service_url = "common/getfilestream/%s";
	
	private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
	protected ImageLoader imageLoader = ImageLoader.getInstance();
	
	private DisplayImageOptions options;	
	
	private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

		static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
				}
			}
		}
	}

	public ListAdAdapter(Activity context, int textViewResourceId, ArrayList<AdsModel> mApps) {
		super(context, textViewResourceId, mApps);
		this.mApps = new ArrayList<AdsModel>();
		this.mApps.addAll(mApps);
		this.context = context;
		mStdImg = context.getResources().getDrawable(R.drawable.no_image);
		
		imageLoader.init(ImageLoaderConfiguration.createDefault(context));
		options = new DisplayImageOptions.Builder()
		//.showImageOnLoading(R.drawable.ic_stub)
		.showImageForEmptyUri(R.drawable.ic_empty)
		.showImageOnFail(R.drawable.ic_error)
		.cacheInMemory(true)
		.cacheOnDisc(true)
		.imageScaleType(ImageScaleType.EXACTLY)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.displayer(new RoundedBitmapDisplayer(20))
		.build();
	}
	
	public void updateNewAdsModelList(ArrayList<AdsModel> mApps){
		this.mApps.clear();
		this.mApps.addAll(mApps);
		this.notifyDataSetChanged();
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		AppViewHolder holder;
		if (convertView == null) {
			holder = new AppViewHolder();
			LayoutInflater inflater = LayoutInflater.from(context);
			convertView = inflater.inflate(R.layout.item_list_menu, null);
			holder.mTitle = (TextView) convertView.findViewById(R.id.tvName);
			holder.mIcon = (ImageView) convertView.findViewById(R.id.imgIcon);
			holder.mRatingstar = (com.alt.libs.DisableRatingbar) convertView.findViewById(R.id.rtViewVip);
			holder.mImgNew = (ImageView) convertView.findViewById(R.id.rlNew);
			holder.mPrice = (TextView) convertView.findViewById(R.id.tvPrice);
			
			convertView.setTag(holder);
		} else {
			holder = (AppViewHolder) convertView.getTag();
		}
		try {
			
			Log.e("ListAdAdapter Log:", String.valueOf(position));
			
			final AdsModel app = mApps.get(position);
			
			holder.setTitle(app.getCode());

			DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");// ("yyyy/MM/dd HH:mm:ss");
																		// need
																		// to
																		// compare
																		// time
																		// here
																		// ?
			Date date = new Date();

			int currentdate = Integer.parseInt(dateFormat.format(date)) - Integer.parseInt(app.getApproveddate());

			if (currentdate >= 0 && currentdate <= 5) {
				// holder.setControlVisible(holder.mImgNew, View.VISIBLE);
				holder.mImgNew.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.bg_new));
			} else {
				// holder.setControlVisible(holder.mImgNew, View.GONE);
				holder.mImgNew.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.bg_no_new));
			}

			if (app.getRating() == null || app.getRating().equals("0")) {
				holder.setControlVisible(holder.mRatingstar, View.GONE);
			} else {
				holder.setControlVisible(holder.mRatingstar, View.VISIBLE);
				holder.setRating(Integer.parseInt(app.getRating()) > 5 ? 5 : Integer.parseInt(app.getRating()));
			}
			// set image
//			if (mIcons == null || mIcons.get(app.getAdsid()) == null) {
//				holder.setIcon(mStdImg);
//			} else {				
//				InputStream inputStream = new ByteArrayInputStream(mIcons.get(app.getAdsid()));
//				Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
//				holder.mIcon.setImageBitmap(ALTSysUtils.getRoundedBitmap(bitmap, 40));
//				bitmap.recycle();
//			}
						
			holder.setPrice(app.getFee());
			
			convertView.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					
					imageLoader.clearMemoryCache();
					imageLoader.clearDiscCache();
					imageLoader.stop();
					
					Bundle cmdData = new Bundle();
					cmdData.putString("AdsID", app.getAdsid());	
					ALTAppMgr.getInstance().startServiceCmd(CMCmdHandler.COMMAND_GET_ADS_IMAGE_LIST, new CMCmdHandler(), cmdData,true);
					// ALTBaseActivity.onEventReceiver(SCREEN_UI.VIEWIMAGE);
				}
			});
			
			imageLoader.displayImage(RestClient.apiUrl(ALTSysUtils.format(service_url, app.getImageId())), holder.mIcon, options, animateFirstListener);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return convertView;
	}


	@Override
	public int getCount() {
		return mApps.size();
	}

	public AdsModel getItem(int position) {
		return mApps.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public void setIcons(Map<String, byte[]> icons) {
		this.mIcons = icons;
	}

	public class AppViewHolder {

		private TextView mTitle;
		private TextView mPrice;
		private ImageView mIcon;
		private com.alt.libs.DisableRatingbar mRatingstar;
		private ImageView mImgNew;

		public void setTitle(String title) {
			mTitle.setText(title);
		}
		
		public void setPrice(String price) {
			formatter = new DecimalFormat("#,###,###");
			price = formatter.format(Double.parseDouble(price)).replace(",", ".");
			mPrice.setText(price);
		}


		public void setIcon(Drawable img) {
			if (img != null) {
				mIcon.setImageDrawable(img);
			}
		}

		public void setRating(int numStars) {
			mRatingstar.setNumStars(numStars);
		}

		public void setControlVisible(View v, int status) {
			v.setVisibility(status);
		}

	}
}
